<template>
  <div class="add-wrap">
    <!-- <div class="body">
      <div class="body-left">  -->
    <div class="project" v-loading="uploadLoading">
      <el-form
        :model="basicForm"
        label-position="top"
        :rules="basicRules"
        ref="basicFormRef"
      >
        <!-- 基本信息 -->
        <div class="project-part">
          <div class="project-part-title">基本信息</div>
          <div class="project-part-content">
            <!-- 统一的动态表单字段渲染 -->
            <el-row
              v-for="(group, gIndex) in groupedFormFields"
              :key="`form-${gIndex}`"
            >
              <el-col
                v-for="field in group"
                :key="field.key"
                :sm="24"
                :md="12"
                :lg="8"
                :xl="6"
              >
                <el-form-item
                  :label="field.label"
                  :prop="field.required ? field.key : ''"
                >
                  <!-- input -->
                  <el-input
                    v-if="field.component === 'input'"
                    v-model="basicForm[field.key]"
                    :placeholder="
                      field.placeholder || '请输入'
                    "
                    :type="field.type || 'text'"
                    :rows="
                      field.type === 'textarea'
                        ? field.rows || 3
                        : undefined
                    "
                    :class="
                      field.type === 'textarea'
                        ? 'resize-textarea'
                        : ''
                    "
                    :disabled="isDetail"
                  />
                  <!-- select -->
                  <el-select
                    v-else-if="field.component === 'select'"
                    v-model="basicForm[field.key]"
                    clearable
                    :placeholder="
                      field.placeholder || '请选择'
                    "
                    :disabled="isDetail"
                    :multiple="field.multiple"
                    :filterable="field.filterable"
                    @change="
                      handleFieldChange(field.key, $event)
                    "
                  >
                    <el-option
                      v-for="item in getOptions(
                        field.optionsKey
                      )"
                      :key="item.value ? item.value : item"
                      :label="
                        item.label ? item.label : item
                      "
                      :value="
                        item.value ? item.value : item
                      "
                    />
                  </el-select>
                  <!-- radio -->
                  <el-radio-group
                    v-else-if="field.component === 'radio'"
                    v-model="basicForm[field.key]"
                    :disabled="isDetail"
                  >
                    <el-radio
                      v-for="option in field.options"
                      :key="option"
                      :label="option"
                    >
                      {{ option }}
                    </el-radio>
                  </el-radio-group>
                  <!-- date -->
                  <el-date-picker
                    v-else-if="field.component === 'date'"
                    v-model="basicForm[field.key]"
                    type="date"
                    :disabled="isDetail"
                    :placeholder="
                      field.placeholder || '选择日期'
                    "
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 项目范围 -->
        <div class="boundary">
          <div class="project-part">
            <div class="project-part-title">项目范围</div>
            <!-- <el-row>
                <el-col>
                  <el-form-item label="文件类型">
                    <el-radio-group
                      v-model="fileType"
                      :disabled="isDetail"
                      @change="basicForm.range = ''"
                    >
                      <el-radio label="shp"></el-radio>
                      <el-radio label="geojson"></el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row> -->

            <!-- <el-row
                :gutter="24"
                v-if="fileType === 'geojson'"
              >
                <el-col :span="24">
                  <el-form-item
                    label="项目红线图文件（geojson格式）"
                  >
                    <el-input
                      v-model="basicForm.range"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                    <el-button
                      size="small"
                      class="preview-button"
                      @click="previewMap"
                      >地图预览</el-button
                    >
                  </el-form-item>
                </el-col>
              </el-row> -->

            <el-row
              :gutter="24"
              v-if="fileType_motioned === 'shp'"
            >
              <el-col :span="24">
                <el-form-item
                  label="项目设计示意范围线文件（shp格式）"
                >
                  <el-upload
                    action="#"
                    class="shp-upload"
                    :show-file-list="false"
                    :drag="false"
                    :on-change="
                      (file) =>
                        onFileSelect(file, 'motionedRange')
                    "
                    :auto-upload="false"
                    v-if="!isDetail"
                    accept=".zip"
                  >
                    <span>
                      <span class="shp-upload-icon"></span>
                      <span class="shp-upload-text"
                        >点击上传</span
                      >
                    </span>
                  </el-upload>
                  <el-input
                    v-model="basicForm.motionedRange"
                    placeholder="支持输入geojson"
                    :disabled="isDetail"
                    clearable
                  ></el-input>
                  <el-progress
                    v-if="
                      progressNum_motioned !== 0 &&
                      progressNum_motioned !== 100
                    "
                    :percentage="progressNum_motioned"
                    color="#409eff"
                  ></el-progress>
                  <el-button
                    size="small"
                    class="preview-button"
                    @click="
                      previewMap(basicForm.motionedRange)
                    "
                    v-if="basicForm.motionedRange"
                    >地图预览</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24" v-if="fileType === 'shp'">
              <el-col :span="24">
                <el-form-item
                  label="项目红线图文件（shp格式）"
                >
                  <el-upload
                    action="#"
                    class="shp-upload"
                    :show-file-list="false"
                    :drag="false"
                    :on-change="
                      (file) => onFileSelect(file, 'range')
                    "
                    :auto-upload="false"
                    v-if="!isDetail"
                    accept=".zip"
                  >
                    <span>
                      <span class="shp-upload-icon"></span>
                      <span class="shp-upload-text"
                        >点击上传</span
                      >
                    </span>
                  </el-upload>
                  <el-input
                    v-model="basicForm.range"
                    placeholder="支持输入geojson"
                    :disabled="isDetail"
                    clearable
                  ></el-input>
                  <el-progress
                    v-if="
                      progressNum !== 0 &&
                      progressNum !== 100
                    "
                    :percentage="progressNum"
                    color="#409eff"
                  ></el-progress>
                  <el-button
                    size="small"
                    class="preview-button"
                    @click="previewMap(basicForm.range)"
                    v-if="basicForm.range"
                    >地图预览</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 项目效果图 -->
        <div class="project-part">
          <div class="project-part-title">项目效果图</div>
          <el-upload
            class="upload-image"
            action=""
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleChangeImage"
            :on-remove="handleRemoveImage"
            :on-preview="handlePreviewImage"
            :show-file-list="true"
            :file-list="fileList"
            v-if="!isDetail"
            multiple
            accept="image/*"
          >
            <i class="el-icon-plus"></i>
          </el-upload>

          <el-dialog
            :visible.sync="previewVisible"
            width="50%"
            v-if="!isDetail"
          >
            <img
              :src="previewImage"
              alt="预览"
              style="width: 100%"
            />
          </el-dialog>
          <el-image
            v-for="item in fileList"
            :preview-src-list="previewImageList"
            :key="item.url"
            :src="item.url"
            v-if="isDetail"
            class="image"
          >
          </el-image>
        </div>
      </el-form>

      <customizeDialog
        :visible="dialogMapVisible"
        @update:visible="dialogMapVisible = $event"
        ref="dialog"
        :title="`${headerTitle}`"
        :titleTip="`当前面积：${currentArea}m²`"
        :width="'1200px'"
        top="100px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :has-footer="false"
        customPadding="0px"
      >
        <div
          v-loading="mapLoading"
          element-loading-text="文件正在解析中，请稍后..."
        >
          <MapView
            :viewer-id="viewerId"
            :key="countMapLoad"
            @onload="onMapLoad"
          />
          <Utool
            :viewerId="viewerId"
            :position="{ top: '60px', right: '20px' }"
            :t="[]"
            :b="[
              {
                title: '初始位置',
                icon: 'dingwei'
              }
            ]"
            :showMore="false"
          ></Utool>
        </div>
      </customizeDialog>
    </div>
    <!-- </div> -->

    <!--      <div class="body-right">-->
    <!--        <div class="project-part">-->
    <!--          <div class="top">-->
    <!--            <div class="project-part-title">进度信息</div>-->

    <!--            <el-button-->
    <!--              icon="el-icon-plus"-->
    <!--              @click="addProcess"-->
    <!--              class="add-btn"-->
    <!--              v-if="!isDetail"-->
    <!--              >新增进度</el-button-->
    <!--            >-->
    <!--          </div>-->
    <!--        </div>-->

    <!--        <ProgressInfo-->
    <!--          ref="progressInfo"-->
    <!--          :key="progressInfoKey"-->
    <!--          :dataList="basicForm.processDetailRelList"-->
    <!--          :isDetail="isDetail"-->
    <!--          @edit="editProgress"-->
    <!--          @delete="deleteProgress"-->
    <!--        ></ProgressInfo>-->
    <!--      </div>-->
    <!-- </div> -->

    <ProgressDialog
      :visible.sync="showDialog"
      title="项目进展信息"
      :editIndex="editIndex"
      :currentData="currentData"
      :currentInfo="currentInfo"
      @confirm="handleSubmit"
      @resetEditIndex="resetEditIndex"
    />
  </div>
</template>

<script>
import {
  batchSelectionOptions,
  projectTypeOptions,
  projectSecondTypeOptions,
  ownerConstructionOptions,
  isGovernInvest,
  maturityOptions,
  landUseOptions,
  // investorOptions,
  landingMethodOptions,
  fundBuildSourceOptions,
  projectStatusTypeOptions
} from '@/utils/project/data'
import MapView from '@/components/mapView'
import Utool from '@/components/utool/index-land'
import customizeDialog from '@/components/checkHistory/customizeDialog.vue'
import { dwgFileById } from '@/api/projectMessage'
import * as turf from '@turf/turf'
import request from '@/utils/request'
import { STATIC_FILE_URL } from '@/api/config.js'
import ProgressDialog from '@/views/dataManagement/projectManagement/constructProjectInfo/components/components/addProgressDialog.vue'
import ProgressInfo from '@/views/dataManagement/projectManagement/constructProjectInfo/components/components/progressInfo.vue'
import {
  queryInvestorOptions,
  getTemplateInfo,
  getElementInfo
} from '@/api/dataManagement'

let _layerManager, _viewer

export default {
  props: {
    isEdit: Boolean,
    isDetail: Boolean,
    detailInfo: Object,
    baseInfoData: Object
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        fundBuildSource: '',
        landingMethod: '',
        processDetailRelList: [],
        isBasicFormReady: false,
        isBasicFormChanged: false
      },
      basicRules: {
        year: [
          {
            required: true,
            message: '请选择年度',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur'
          }
        ],
        projectBusinessDepartType: [
          {
            required: true,
            message: '请选择项目类型Ⅱ',
            trigger: 'blur'
          }
        ],
        maturity: [
          {
            required: true,
            message: '请选择项目阶段',
            trigger: 'blur'
          }
        ],
        ownerPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确手机号码',
            trigger: 'blur'
          }
        ],
        sendPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确手机号码',
            trigger: 'blur'
          }
        ],
        investor: [
          {
            required: true,
            message: '请选择投资主体',
            trigger: 'blur'
          }
        ],
        fundBuildSource: [
          {
            required: true,
            message: '请选择资金来源',
            trigger: 'blur'
          }
        ],
        landingMethod: [
          {
            required: true,
            message: '请选择落地方式',
            trigger: 'blur'
          }
        ]
      },
      yearList: [],
      maturityList: ['成熟', '基本成熟', '意向项目'],
      uploadLoading: false,
      progressNum_motioned: 0,
      progressNum: 0,
      dialogMapVisible: false,
      mapLoading: false,
      headerTitle: '',
      countMapLoad: 0,
      currentFeature: '',
      currentArea: 0,
      fileType_motioned: 'shp',
      fileType: 'shp',
      viewerId: 'dwgMap',
      uploadFileList: [],
      roleList: [],
      previewImage: '',
      previewVisible: false,
      previewImageList: [],
      fileList: [],
      showDialog: false,
      editIndex: -1,
      currentData: {},
      currentInfo: {},
      progressInfoKey: 0,
      investorOptions: [],

      // 统一的表单字段配置
      formFields: [
        // 第一行：年度、项目名称、最终项目名称
        {
          label: '年度',
          key: 'year',
          component: 'select',
          optionsKey: 'yearList',
          required: true,
          multiple: true,
          visible: true
        },
        {
          label: '项目名称/立项名称',
          key: 'name',
          component: 'input',
          required: true,
          visible: true
        },
        {
          label: '项目名称备注（与区平台相同）',
          key: 'nameRemark',
          component: 'input',
          visible: true
        },
        {
          label: '项目备案号/项目代码',
          key: 'code',
          component: 'input',
          visible: true
        },

        // 第二行：项目详细地址、项目位置经纬度、资金来源、落地方式
        {
          label: '项目详细地址',
          key: 'address',
          component: 'input',
          visible: true
        },
        {
          label: '项目位置经纬度',
          key: 'location',
          component: 'input',
          visible: true
        },
        {
          label: '资金来源',
          key: 'fundBuildSource',
          component: 'select',
          optionsKey: 'fundBuildSourceOptions',
          required: true,
          visible: true
        },
        {
          label: '落地方式',
          key: 'landingMethod',
          component: 'select',
          optionsKey: 'landingMethodOptions',
          required: true,
          visible: false // 动态显示
        },

        // 第三行：总投资、批次、项目类型、项目类型Ⅱ
        {
          label: '总投资(万元)',
          key: 'investmentTotal',
          component: 'input',
          visible: true
        },
        {
          label: '批次',
          key: 'batchNo',
          component: 'select',
          optionsKey: 'batchSelectionOptions',
          visible: true
        },
        {
          label: '项目类型',
          key: 'projectBusinessType',
          component: 'select',
          optionsKey: 'projectTypeOptions',
          visible: true
        },
        {
          label: '项目类型Ⅱ',
          key: 'projectBusinessDepartType',
          component: 'select',
          optionsKey: 'projectSecondTypeOptions',
          required: true,
          visible: true
        },

        // 第四行：项目阶段、项目状态、计划开工时间、计划竣工时间
        {
          label: '项目阶段',
          key: 'maturity',
          component: 'select',
          optionsKey: 'maturityOptions',
          required: true,
          visible: true
        },
        {
          label: '项目状态',
          key: 'status',
          component: 'select',
          optionsKey: 'projectStatusTypeOptions',
          visible: true
        },
        {
          label: '计划开工时间',
          key: 'planStartTime',
          component: 'date',
          visible: true
        },
        {
          label: '计划竣工时间',
          key: 'planEndTime',
          component: 'date',
          visible: true
        },

        // 第五行：投资主体、业主、业主联系人、业主联系人手机
        {
          label: '投资主体',
          key: 'investor',
          component: 'select',
          optionsKey: 'investorOptions',
          required: true,
          visible: true
        },
        {
          label: '业主(建设单位)',
          key: 'ownerUnit',
          component: 'input',
          visible: true
        },
        {
          label: '业主联系人',
          key: 'ownerContract',
          component: 'input',
          visible: true
        },
        {
          label: '业主联系人手机',
          key: 'ownerPhone',
          component: 'input',
          visible: true
        },

        // 第六行：报送人联系手机、是否省重点、是否市重点、是否区重点
        {
          label: '报送人联系手机',
          key: 'sendPhone',
          component: 'input',
          visible: true
        },
        {
          label: '是否省重点',
          key: 'provinceImportantFlag',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },
        {
          label: '是否市重点',
          key: 'cityImportantFlag',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },
        {
          label: '是否区重点',
          key: 'importantFlag',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },

        // 第七行：是否区重推、是否需要供地、建设内容及规模、用地面积
        {
          label: '是否区重推',
          key: 'importantSuggestionFlag',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },
        {
          label: '是否需要供地',
          key: 'supportLandFlag',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },
        {
          label: '建设内容及规模',
          key: 'buildContentScale',
          component: 'input',
          type: 'textarea',
          visible: true
        },
        {
          label: '用地面积(万平方米)',
          key: 'landArea',
          component: 'input',
          visible: true
        },

        // 第八行：已建成房屋面积、已建成道路长度、已建成景观面积、已建成公园绿道面积
        {
          label: '已建成房屋面积(万平方米)',
          key: 'buildHouseArea',
          component: 'input',
          visible: true
        },
        {
          label: '已建成道路长度(公里)',
          key: 'buildRoadLength',
          component: 'input',
          visible: true
        },
        {
          label: '已建成景观面积(万平方米)',
          key: 'buildSceneryArea',
          component: 'input',
          // type: 'number',
          visible: true
        },
        {
          label: '已建成公园绿道长度(公里)',
          key: 'buildParkArea',
          component: 'input',
          // type: 'number',
          visible: true
        },

        // 第九行：投用时间、是否纳入重要目标统计
        {
          label: '投用时间',
          key: 'useTime',
          component: 'date',
          visible: true
        },
        {
          label: '是否纳入重要目标统计',
          key: 'totalFlag',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        }
      ],

      fundBuildSource: '',
      landingMethod: '',
      blankTemplateInfo: [],
      blankElementList: []
    }
  },
  components: {
    MapView,
    Utool,
    customizeDialog,
    ProgressDialog,
    ProgressInfo
  },
  computed: {
    titles() {
      return [this.title]
    },
    batchSelectionOptions() {
      return batchSelectionOptions
    },
    projectTypeOptions() {
      return projectTypeOptions
    },
    projectSecondTypeOptions() {
      return projectSecondTypeOptions
    },
    ownerConstructionOptions() {
      return ownerConstructionOptions
    },
    isGovernInvest() {
      return isGovernInvest
    },
    landUseOptions() {
      return landUseOptions
    },
    maturityOptions() {
      return maturityOptions
    },
    fundBuildSourceOptions() {
      return fundBuildSourceOptions
    },
    landingMethodOptions() {
      return landingMethodOptions
    },
    projectStatusTypeOptions() {
      return projectStatusTypeOptions
    },

    // 统一分组后的表单字段
    groupedFormFields() {
      const visibleFields = this.formFields.filter(
        (field) => {
          // 根据字段key判断条件显示
          if (field.key === 'landingMethod') {
            return ['企业投资', '平台公司自筹'].includes(
              this.basicForm.fundBuildSource
            )
          }
          return field.visible
        }
      )

      const result = []
      for (let i = 0; i < visibleFields.length; i += 4) {
        result.push(visibleFields.slice(i, i + 4))
      }
      return result
    }
  },
  created() {
    const currentYear = new Date().getFullYear()
    this.yearList = Array.from(
      { length: 5 },
      (_, i) => currentYear - 4 + i
    ).sort((a, b) => b - a)
    this.getInvestorOptions()
  },
  watch: {
    'basicForm.maturity'(newMaturity) {
      if (
        this.basicForm.processDetailRelList &&
        this.basicForm.processDetailRelList.length > 0
      ) {
        // 使用 Vue.set 确保响应式更新
        this.$set(
          this.basicForm.processDetailRelList[0],
          'maturity',
          newMaturity
        )

        // 强制更新进度信息组件
        this.progressInfoKey++

        // 确保子组件也能及时更新
        this.$nextTick(() => {
          if (this.$refs.progressInfo) {
            this.$refs.progressInfo.$forceUpdate()
            this.$refs.progressInfo.updateImageLists()
          }
        })
      }
    },
    'basicForm.processDetailRelList': {
      handler(newList) {
        // 更新 key 强制重新渲染子组件
        this.progressInfoKey++
        // 强制更新子组件
        this.$nextTick(() => {
          if (this.$refs.progressInfo) {
            this.$refs.progressInfo.$forceUpdate()
          }
        })
      },
      deep: true
    },
    basicForm: {
      handler() {
        if (this.isBasicFormReady === true) {
          this.isBasicFormChanged = true
        }
      },
      deep: true
    },
    detailInfo: {
      handler(val) {
        if (val.pkid) {
          this.basicForm = this.detailInfo

          this.updateFundBuildSourceAndLandingMethod()

          if (
            val.resourceFileInfos &&
            val.resourceFileInfos.length
          ) {
            this.fileList = val.resourceFileInfos.map(
              (item) => {
                return {
                  ...item,
                  url: `${STATIC_FILE_URL}${item.filePath}`
                }
              }
            )

            if (this.isDetail) {
              this.previewImageList = this.fileList.map(
                (item) => item.url
              )
            }

            this.uploadFileList = JSON.parse(
              JSON.stringify(this.fileList)
            )
          }
        }
      },
      immidiate: true
    }
  },
  methods: {
    setInfoReady() {
      setTimeout(() => {
        this.isBasicFormReady = true
        this.isBasicFormChanged = false
      }, 300)
    },
    formatTemplateList(list, isNew) {
      return list.map((newItem, index) => {
        if (isNew && 'pkid' in newItem) {
          newItem.processNodeId = newItem.pkid
          newItem.pkid = ''
          newItem.createTime = ''
          newItem.createUser = ''
          newItem.updateTime = ''
          newItem.updateUser = ''
          if (index == 0) {
            newItem.selected = '1'
            newItem.nodeStatus = '办理中'
          }
        }
        return newItem
      })
    },
    formatElementTemplateList(list, isNew) {
      const arr = list.map((item, index) => {
        // 如果是新增状态，并且 item 中有 pkid 字段
        if (isNew && 'pkid' in item) {
          item.pkid = ''
          item.createTime = ''
          item.updateTime = ''
          item.updateUser = ''

          if (index == 0) {
            item.selected = '1'
            item.status = '办理中'
          }
        }

        return item
      })

      return arr
    },

    // 获取模板信息
    getTemplateData() {
      getTemplateInfo({
        fundBuildSource: this.fundBuildSource,
        landingMethod: this.landingMethod
      }).then((res) => {
        this.blankTemplateInfo = this.formatTemplateList(
          res.data,
          true
        )
      })
    },

    // 获取要素列表
    getElementData() {
      getElementInfo({
        fundBuildSource: this.fundBuildSource,
        landingMethod: this.landingMethod
      })
        .then((res) => {
          this.blankElementList =
            this.formatElementTemplateList(
              res.data[0].resourceDictItems,
              true
            )
        })
        .catch((e) => {
          console.error('e', e)
        })
    },
    updateFundBuildSourceAndLandingMethod() {
      // 资金来源
      this.fundBuildSource =
        this.basicForm.fundBuildSource || ''
      // 拿地方式
      if (
        ['政府投资', '其他', ''].includes(
          this.fundBuildSource
        )
      ) {
        this.landingMethod = ''
        this.basicForm.landingMethod = ''
      } else {
        this.landingMethod =
          this.basicForm.landingMethod || ''
      }

      console.log(
        'this.fundBuildSource',
        this.fundBuildSource
      )
      console.log('this.landingMethod', this.landingMethod)

      if (
        ['政府投资', '其他'].includes(
          this.fundBuildSource
        ) ||
        (this.fundBuildSource && this.landingMethod)
      ) {
        this.getTemplateData()
        this.getElementData()
      }
    },

    getInvestorOptions() {
      queryInvestorOptions().then((res) => {
        this.investorOptions = res.data.list.map(
          (item) => item.name
        )
      })
    },
    getFormData() {
      return this.basicForm
    },
    validateForm(callback) {
      this.$refs.basicFormRef.validate(callback)
    },
    // 显示项目成熟度帮助信息
    showMaturityHelp() {
      // 这个方法可以用于处理点击事件，目前tooltip已经能满足需求
    },

    // 获取字段选项
    getOptions(optionsKey) {
      const optionsMap = {
        yearList: this.yearList,
        batchSelectionOptions: this.batchSelectionOptions,
        projectTypeOptions: this.projectTypeOptions,
        projectSecondTypeOptions:
          this.projectSecondTypeOptions,
        maturityOptions: this.maturityOptions,
        fundBuildSourceOptions: this.fundBuildSourceOptions,
        landingMethodOptions: this.landingMethodOptions,
        projectStatusTypeOptions:
          this.projectStatusTypeOptions,
        investorOptions: this.investorOptions
      }
      return optionsMap[optionsKey] || []
    },

    // 处理字段变化
    handleFieldChange(fieldKey, value) {
      // 如果是项目阶段变化，同步到进度信息
      if (fieldKey === 'maturity') {
        if (
          this.basicForm.processDetailRelList &&
          this.basicForm.processDetailRelList.length > 0
        ) {
          this.$set(
            this.basicForm.processDetailRelList[0],
            'maturity',
            value
          )
        }
      } else if (fieldKey == 'fundBuildSource') {
        // const oriFundBuildSource = this.baseInfoData?.baseMess?.fundBuildSource
        if (this.fundBuildSource) {
          this.$confirm(
            '修改【资金来源】将会导致项目进度信息重置，是否继续？',
            '注意',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              this.updateFundBuildSourceAndLandingMethod()
            })
            .catch(() => {
              this.basicForm.fundBuildSource =
                this.fundBuildSource
            })
        } else {
          this.updateFundBuildSourceAndLandingMethod()
        }
      } else if (fieldKey == 'landingMethod') {
        // const oriLandingMethod = this.baseInfoData?.baseMess?.landingMethod
        if (this.landingMethod) {
          this.$confirm(
            '修改【落地方式】将会导致项目进度信息重置，是否继续？',
            '注意',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              this.updateFundBuildSourceAndLandingMethod()
            })
            .catch(() => {
              this.basicForm.landingMethod =
                this.landingMethod
            })
        } else {
          this.updateFundBuildSourceAndLandingMethod()
        }
      }
    },

    // 上传文件
    onFileSelect(file, type) {
      this.uploadLoading = true
      const data = new FormData()
      data.append('file', file.raw)
      request({
        method: 'post',
        url: '/pad/common/importData',
        data: data,
        onUploadProgress: (progressEvent) => {
          const process = parseInt(
            ((progressEvent.loaded / progressEvent.total) *
              100) |
              0,
            10
          )
          if (type == 'range') {
            this.progressNum = process
          } else {
            this.progressNum_motioned = process
          }
        }
      })
        .then((res) => {
          if (res.success) {
            // const id = res.data.fileId
            // const geojson = res.data.geoJson
            // this.$set(this.basicForm, 'fileName', file.name)
            // this.$set(this.basicForm, 'shpFile', id)
            // this.$set(this.basicForm, 'shpJson', geojson)
            // this.$set(this.basicForm, 'range', geojson)
            // this.basicForm.range = res.data
            this.basicForm[type] = res.data
            this.$message.success('上传成功')
          } else {
            this.$message.error(res.message)
          }

          this.uploadLoading = false
        })
        .catch(() => {
          this.uploadLoading = false
        })
    },

    // 地图预览
    previewMap(range) {
      // if (this.basicForm.range) {
      if (range) {
        this.viewByGeojson(range)
        this.dialogMapVisible = true
      } else {
        this.$message.warning(
          '请先上传文件或者填写geojson再预览'
        )
      }
    },

    // 通过文件id预览
    previewMapById(id, geojsonStr) {
      this.headerTitle = '地图预览'
      this.mapLoading = true

      if (!geojsonStr) {
        dwgFileById(id)
          .then((res) => {
            if (res.success) {
              this.currentFeature = JSON.parse(res.data)
              const area = turf.area(this.currentFeature)
              this.currentArea = area ? area.toFixed(2) : 0
              // 更新地图预览
              this.countMapLoad++
            }
            this.mapLoading = false
          })
          .catch(() => {
            this.mapLoading = false
          })
      } else {
        this.currentFeature = JSON.parse(geojsonStr)
        const area = turf.area(this.currentFeature)
        this.currentArea = area ? area.toFixed(2) : 0
        // 更新地图预览
        this.countMapLoad++
        this.mapLoading = false
      }
    },

    // 通过geojson预览
    viewByGeojson(range) {
      // this.currentFeature = JSON.parse(this.basicForm.range)
      this.currentFeature = JSON.parse(range)
      const area = turf.area(this.currentFeature)
      this.currentArea = area ? area.toFixed(2) : 0
      // 更新地图预览
      this.countMapLoad++
      this.mapLoading = false
    },

    // 地图加载
    onMapLoad({ id, viewer }) {
      _viewer = viewer

      _viewer.scene.imageryLayers.addImageryProvider(
        new Cesium.TiandituImageryProvider({
          mapStyle: null,
          token: 'a49a9220798216424e34b531cb3fa5b2',
          url: 'https://t0.tianditu.gov.cn/img_w/wmts'
        }),
        0
      )
      const geojson = _viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load(this.currentFeature)
      )
      _viewer.flyTo(geojson)
    },

    handleRemoveImage(file) {
      file.name
        ? (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.name !== file.name
          ))
        : (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.url !== file.url
          ))
    },

    handleChangeImage(file) {
      this.uploadFileList.push(file.raw)
    },

    handlePreviewImage(file) {
      if (file.url) {
        this.previewImage = file.url
      } else if (file.raw) {
        this.previewImage = URL.createObjectURL(file.raw)
      }
      this.previewVisible = true
    },

    getEffectList() {
      return this.uploadFileList
    },

    handleSubmit(data) {
      // 处理图片数据
      const processedData = {
        ...data,
        progressImages: []
      }

      // 使用 Set 来存储已处理的 filePath，避免重复
      const processedPaths = new Set()
      // 处理图片数据
      if (
        data.progressImages &&
        Array.isArray(data.progressImages)
      ) {
        data.progressImages.forEach((img) => {
          // 如果是已上传的图片（有 filePath）
          if (
            img.filePath &&
            !processedPaths.has(img.filePath)
          ) {
            processedPaths.add(img.filePath)
            processedData.progressImages.push({
              filePath: img.filePath,
              pkid: img.pkid,
              url: `${STATIC_FILE_URL}${img.filePath}`,
              isUploaded: true
            })
          }
          // 如果是新上传的图片（File 对象或 raw）
          else if (img instanceof File || img.raw) {
            const file = img.raw || img
            const url = img.url || URL.createObjectURL(file)
            processedData.progressImages.push({
              url,
              raw: file,
              isUploaded: false
            })
          }
          // 如果已经是处理过的对象
          else if (
            img &&
            !processedPaths.has(img.filePath)
          ) {
            processedPaths.add(img.filePath)
            processedData.progressImages.push(img)
          }
        })
      }

      // 生成 imageIds
      const imageIds = []
      processedData.progressImages.forEach((img) => {
        if (img.pkid) imageIds.push(img.pkid)
        else if (img.uid) imageIds.push(img.uid.toString())
        else if (img.raw && img.raw.uid)
          imageIds.push(img.raw.uid.toString())
      })
      processedData.progressPicture = imageIds.join(',')
      if (imageIds.length === 0) {
        processedData.progressPicture = ''
      }

      if (this.editIndex > -1) {
        // 编辑现有进度信息
        // 使用 Vue.set 确保响应式更新
        this.$set(
          this.basicForm.processDetailRelList,
          this.editIndex,
          processedData
        )

        // 如果编辑的是第一条，需要同步基本信息
        if (this.editIndex === 0) {
          this.basicForm.maturity = processedData.maturity
        }
      } else {
        // 新增进度信息，插入到最前面成为第一条
        if (!this.basicForm.processDetailRelList) {
          this.$set(
            this.basicForm,
            'processDetailRelList',
            []
          )
        }
        // 使用 unshift 而不是直接赋值
        this.basicForm.processDetailRelList.unshift(
          processedData
        )
        // 新增的进度信息成为第一条，同步基本信息
        this.basicForm.maturity = processedData.maturity
      }

      // 重置编辑索引
      this.editIndex = -1

      // 强制触发响应式更新
      this.$set(this.basicForm, 'processDetailRelList', [
        ...this.basicForm.processDetailRelList
      ])

      // 更新 key 强制重新渲染子组件
      this.progressInfoKey++

      // 强制更新视图
      this.$nextTick(() => {
        // 强制更新整个组件
        this.$forceUpdate()

        // 强制更新子组件
        if (this.$refs.progressInfo) {
          this.$refs.progressInfo.$forceUpdate()
          // 手动触发子组件的 watch
          this.$refs.progressInfo.updateImageLists()
        }
      })

      // 关闭对话框
      this.showDialog = false
    },

    editProgress(item, index) {
      this.editIndex = index
      // 直接用 processDetailRelList[index] 作为编辑对象，确保引用同步
      const realItem =
        this.basicForm.processDetailRelList[index]
      // 强制更新数据，确保使用最新状态
      this.$nextTick(() => {
        // 处理图片数据
        const processedData = {
          ...realItem,
          progressImages: []
        }

        // 优先使用 progressImages（编辑时的最新状态）
        if (
          realItem.progressImages &&
          Array.isArray(realItem.progressImages)
        ) {
          processedData.progressImages =
            realItem.progressImages.map((img) => {
              if (img.filePath) {
                return {
                  filePath: img.filePath,
                  pkid: img.pkid,
                  url: `${STATIC_FILE_URL}${img.filePath}`,
                  isUploaded: true
                }
              } else if (img.raw) {
                return {
                  url:
                    img.url || URL.createObjectURL(img.raw),
                  raw: img.raw,
                  isUploaded: false
                }
              } else {
                return img
              }
            })
        }

        // 只有在没有 progressImages 时才使用 resourceFileInfos（查询时）
        if (
          processedData.progressImages.length === 0 &&
          realItem.resourceFileInfos &&
          Array.isArray(realItem.resourceFileInfos)
        ) {
          processedData.progressImages =
            realItem.resourceFileInfos.map((img) => ({
              filePath: img.filePath,
              pkid: img.pkid,
              url: `${STATIC_FILE_URL}${img.filePath}`,
              isUploaded: true
            }))
        }

        this.currentData = processedData
        this.currentInfo = {
          maturity: realItem.maturity
            ? realItem.maturity
            : this.basicForm.maturity
        }

        this.showDialog = true
      })
    },

    deleteProgress(index) {
      // 如果删除的是第一条，且还有其他进度信息，需要更新基本信息为新的第一条
      if (
        index === 0 &&
        this.basicForm.processDetailRelList.length > 1
      ) {
        const newFirstItem =
          this.basicForm.processDetailRelList[1]
        this.basicForm.maturity =
          newFirstItem.maturity || this.basicForm.maturity
      }

      this.basicForm.processDetailRelList.splice(index, 1)

      this.$set(
        this.basicForm,
        'progressInfo',
        this.basicForm.processDetailRelList.map((item) => ({
          progressDate: item.progressDate,
          progressDesc: item.progressDesc,
          progressPicture: item.progressPicture
        }))
      )
    },

    addProcess() {
      this.showDialog = true
      this.currentInfo = {
        maturity: this.basicForm.maturity
      }
      // 新增进度时，默认使用基本信息的项目阶段
      this.currentData = {
        maturity: this.basicForm.maturity || '',
        createTime: '',
        workProcess: '',
        problemFlag: '是',
        problemContent: '',
        solveAdvice: '',
        progressImages: []
      }
      this.editIndex = -1
    },

    // 重置editIndex
    resetEditIndex() {
      this.editIndex = -1
    }
  }
}
</script>
<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
::v-deep {
  .file-upload {
    .el-upload {
      position: absolute;
      left: 240px;
      top: -35px;
    }
  }
  .el-icon-location {
    position: absolute;
    top: 6px;
    left: 295px;
    color: #00baff;
    font-size: 25px;
    cursor: pointer;
  }
  .el-dialog {
    .el-dialog__body {
      .content {
        padding: 0;
      }
    }
    .cesium-viewer {
      height: 520px !important;
    }
  }
}

.body {
  display: flex;
  padding: 0 0 0 20px;

  &-left {
    width: 100%;
    border-right: 1px solid #f1f1f1;
    overflow: scroll;
  }

  // &-right {
  //   flex: 1;
  //   padding-left: 10px;
  // }

  .top {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    padding-right: 10px;
  }
}

.operate {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  ::v-deep {
    .save-btn {
      background: #497fa3;
      border: 1px solid #497fa3;
      color: white;
      font-size: 14px;
      width: 80px;
      height: 34px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 0px;
    }
    .cancle-btn {
      font-size: 14px;
      width: 80px;
      height: 34px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #497fa3;
      color: #497fa3;
    }
  }
}

.shp-upload {
  cursor: pointer;
  height: 0px;
  ::v-deep .el-upload {
    position: relative !important;
    right: 0 !important;
    top: 0 !important;
    transform: none !important;
  }

  &-text {
    position: absolute;
    top: -49px;
    left: 260px;
    color: #00baff;
    min-width: 60px;
    line-height: 14px;
  }

  &-icon {
    position: absolute;
    width: 16px;
    height: 14px;
    top: -49px;
    left: 240px;
    background: url('~@/assets/images/wisdom-construction/upload-file.png');
    background-size: 100% 100%;
  }
}

.preview-button {
  position: absolute;
  top: 5px;
  left: 330px;
  background: #497fa3;
  border: 1px solid #497fa3;
  border-radius: 2px;
  color: white;
}

// .boundary {
//   padding: 10px;
// }

.resize-textarea .el-textarea__inner {
  max-height: 72px;
  overflow-y: auto;
}

::v-deep .el-upload-list__item-status-label {
  display: none !important;
}

.project {
  padding-top: 10px;
}

.help-icon {
  width: 16px;
  height: 16px;
  margin-left: 4px;
  cursor: pointer;
  vertical-align: middle;
  opacity: 0.6;
  transition: opacity 0.3s;
}

.help-icon:hover {
  opacity: 1;
}

::v-deep .maturity-tooltip {
  max-width: 400px;
}

::v-deep .maturity-tooltip .tooltip-item {
  margin-bottom: 8px;
  line-height: 1.4;
}

::v-deep .maturity-tooltip .tooltip-item:last-child {
  margin-bottom: 0;
}

::v-deep .maturity-tooltip .tooltip-item strong {
  color: #409eff;
}
</style>
